'use strict';
import axios from 'axios'
import webStorage from "./webStorage";
import {common} from "@/common/common";

export class httpReq {
    constructor() {
        // 环境的切换
        if (process.env.NODE_ENV === 'development') {  //开发环境
            axios.defaults.baseURL = ''
        } else if (process.env.NODE_ENV === 'debug') { //debug环境
            axios.defaults.baseURL = ''
        } else if (process.env.NODE_ENV === 'production') {  //线上环境
            axios.defaults.baseURL = ''
        }
        axios.defaults.baseURL = '127.0.0.1';
        axios.defaults.baseURL = "http://" + axios.defaults.baseURL + "/api";
    }

    //post 请求
    post(data, successCallback, failureCallBack, errorCallback) {
        console.log("postData:", data,);
        console.log("Url:", axios.defaults.baseURL,);
        axios({
            url: axios.defaults.baseURL,
            method: "POST",
            timeout: 60000,
            headers: {"Content-Type": "application/json"},
            data: data,
        }).then(function (response) {
            handler(response, successCallback, failureCallBack)
        }).catch(errorCallback);
    }

    httpReqStruct(methodKey) {
        let loginState = webStorage.sessionGet(webStorage.GetSessionAuthStateKeyName());
        return {
            jsonrpc: "2.0",
            method: methodKey,
            params: null,
            id: "1",
            auth: loginState ? webStorage.sessionGet(webStorage.GetSessionAuthKeyName()) : null,
        }
    }
}

//处理http请求返回的response
function handler(response, successCallback, failureCallBack) {
    console.log("response信息:", response);
    if (response.status === 200) {
        if (response.data.length < 1) {
            failureCallBack(response)
        }
        let errInfo = response.data[0].error;
        if (errInfo == null) {
            successCallback(response.data[0].result)
        } else {
            console.log("errInfo", errInfo);
            if (errInfo.errcode === -32603) {
                failureCallBack(errInfo)
                return
            }
            if (errInfo.errcode < 0) {
                console.log(errInfo.errcode);
                alert("错误了，马上要退出登录了");

                common.logout()
            }
            failureCallBack(errInfo)
        }
    } else {
        failureCallBack(response.status);
    }
}
